import Axios, { AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router/index'
import { getToken } from '@/utils/auth'
import { useUserStore } from '@/store/modules/user'

interface ResError {
  message: string
  response: AxiosResponse
}

interface MsgOptions {
  message: string
  type?: 'error' | 'success' | 'warning' | 'info'
  duration?: number
}

function elMsg(options: MsgOptions) {
  const { message, type = 'error', duration = 3000 } = options
  ElMessage({ message, type, duration })
}

const baseURL =
  process.env.NODE_ENV === 'development'
    ? '/api'
    : 'http://pj.imxkj.com:10810/api'
// 创建axios实例
const service = Axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL,
  // 超时
  timeout: 60 * 1000
})

// request拦截器
service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  error => {
    console.error(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (res: AxiosResponse): AxiosResponse => {
    const userStore = useUserStore()

    const code = res.data.code || 200
    const { msg } = res.data
    // 二进制数据则直接返回
    if (
      res.request.responseType === 'blob' ||
      res.request.responseType === 'arraybuffer'
    ) {
      return res.data
    }

    if (code === 401) {
      elMsg({ message: '无效的会话，请重新登录' })
      userStore.clearUserInfo() // 清空用户信息
      userStore.backLogin() // 返回登录页
      throw new Error(res.data)
    }

    if (code > 300) {
      elMsg({ message: msg })
      throw new Error(res.data)
    }

    return res.data
  },
  (error: ResError) => {
    const { message, response } = error
    let msg = message
    if (response.status === 401) {
      msg = '无效的会话，请重新登录'
      router.replace('/teacherLogin')
    }

    elMsg({ message: msg })
    return Promise.reject(error)
  }
)

export default service
